package utils

import (
	"bufio"
	"fmt"
	"golang.org/x/text/encoding/simplifiedchinese"
	"os/exec"
)

// 执行 adb 命令的函数
func RunAdbCommand(args ...string) (string, error) {
	cmd := exec.Command("adb", args...)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("adb 命令执行失败: %v, 输出: %s", err, string(output))
	}
	return string(output), nil
}

func RunCommand(name string, args ...string) (string, error) {
	cmd := exec.Command(name, args...)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("shell 命令执行失败: %v, 输出: %s", err, string(output))
	}
	return string(output), nil
}

/**
 * @brief: 	下发指令，并持续获取输出，直到输出结束
 * @author: haitao.lin
 */
func GetOutputContinually(fun func(output string), name string, args ...string) (<-chan struct{}, error) {
	cmd := exec.Command(name, args...)
	closed := make(chan struct{})
	defer close(closed)

	stdoutPipe, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}
	defer stdoutPipe.Close()

	go func() {
		scanner := bufio.NewScanner(stdoutPipe)
		for scanner.Scan() { // 命令在执行的过程中, 实时地获取其输出
			data, err := simplifiedchinese.GB18030.NewDecoder().Bytes(scanner.Bytes()) // 防止乱码
			if err != nil {
				fmt.Println("transfer error with bytes:", scanner.Bytes())
				continue
			}
			fun(string(data))
		}
	}()

	if err = cmd.Run(); err != nil {
		return nil, err
	}
	return closed, nil
}
